import datetime
from calendar import timegm

import jwt
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from ..serializers.account import AuthSerializer
from utils import return_code
from .. import models

class AuthView(APIView):
    authentication_classes = []
    permission_classes = []

    def post(self, request, *args, **kwargs):
        # print(request.user)
        # print(request.auth)
        # 1.获取用户请求发送的用户名 & 密码

        # 2.数据校验（用户名、密码）
        serializer = AuthSerializer(data=request.data)
        if not serializer.is_valid():
            # {username:[用户名不能为空,]}
            # 200， {code:1000 ....}
            return Response({"code": return_code.FIELD_ERROR, "detail": serializer.errors})

        # 3.数据库校验（用户名、密码）
        username = serializer.validated_data.get("username")
        password = serializer.validated_data.get("password")
        user_object = models.UserInfo.objects.filter(username=username, password=password).first()
        if not user_object:
            return Response({"code": return_code.VALIDATE_ERROR, "detail": "用户名或密码错误"})

        # 4.生成jwt token返回
        headers = {
            'typ': 'jwt',
            'alg': 'HS256'
        }
        # 构造payload
        payload = {
            'user_id': user_object.id,  # 自定义用户ID
            'username': user_object.username,  # 自定义用户名
            # 'exp': datetime.datetime.now() + datetime.timedelta(seconds=5)  # 用now()真是血坑
            'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=5)  # 超时时间
        }

        token = jwt.encode(payload=payload, key=settings.SECRET_KEY, algorithm="HS256", headers=headers)

        # 源码里是在decode的时候，会把这个exp的时间戳（换算成秒）与当前的时间戳做比较，就可以判断是否过期，但是你看看人家的now用的是utc时间啊
        # payload_valid = jwt.decode(token, settings.SECRET_KEY, ["HS256"])
        # print(payload_valid['exp'])
        # now = timegm(datetime.datetime.now(tz=datetime.timezone.utc).utctimetuple())
        # print(now)

        return Response({"code": return_code.SUCCESS, "data": {"token": token, 'username': username}})


class TestView(APIView):
    # 经过全局配置的认证类后才执行后续业务
    def get(self, request, *args, **kwargs):
        print(request.user)  # 封装的CurrentUser对象
        print(request.user.user_id)
        print(request.user.username)
        print(request.user.exp)
        print(request.auth)  # token
        return Response("success")